package com.visionet.waveletData.web.service.group;

import com.visionet.waveletData.web.common.utils.PageInfo;
import com.visionet.waveletData.web.entity.group.Group;
import com.visionet.waveletData.web.entity.group.RobotGroup;
import com.visionet.waveletData.web.entity.robot.Robot;
import com.visionet.waveletData.web.repository.group.GroupDao;
import com.visionet.waveletData.web.repository.group.RobotGroupDao;
import com.visionet.waveletData.web.repository.plan.PlanFileDao;
import com.visionet.waveletData.web.repository.robot.RobotDao;
import com.visionet.waveletData.web.service.account.ShiroDbRealm;
import com.visionet.waveletData.web.service.plan.PlayPlanService;
import com.visionet.waveletData.web.vo.GroupVo;
import com.visionet.waveletData.web.vo.RobotGroupVo;
import com.visionet.waveletData.web.vo.RobotVo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by hxpeng on 2017/1/10.
 */

@Service("groupService")
public class GroupService {

    private static final Logger logger = LoggerFactory.getLogger(GroupService.class);

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private RobotGroupDao robotGroupDao;

    @Autowired
    private PlanFileDao planFileDao;

    @Autowired
    private RobotDao robotDao;

    @Autowired
    private PlayPlanService playPlanService;

    /**
     * 根据条件分组列表
     * @param
     * @return
     */
    public Page<GroupVo> findGroupByConditionForList(GroupVo groupVo, PageInfo pageInfo){
        PageRequest pageRequest = null;
        if(pageInfo==null){
            pageInfo = new PageInfo();
            pageInfo.setPageSize(5000);
        }
        pageRequest=this.getPageRequestInfo(pageInfo);
        Page<GroupVo> page = groupDao.findPageGroup(groupVo,pageRequest);
        pageInfo.setTotalCount(page.getNumberOfElements());
        return page;

    }



    @Transactional
    public void addRobotToGroup(RobotGroupVo robotGroupVo){
        String groupId = robotGroupVo.getGroupId();
        String robotId = robotGroupVo.getRobotId();
        Group group = groupDao.findOne(Long.parseLong(groupId));
        if(group == null){
            throw new NullPointerException("分组为空！！！");
        }
        Robot robot = robotDao.findOne(Long.parseLong(robotId));
        if(robot == null || StringUtils.isNotBlank(robot.getInGroupId())){
            throw new RuntimeException("数据异常或该机器人已被加入其他分组");
        }
        ShiroDbRealm.ShiroUser suser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if(suser == null){
            throw new RuntimeException("未登录！！！");
        }
        try {
            if(robotGroupDao.groupDeleteRobot(groupId,robotId) == null){
                robot.setInGroupId(group.getId().toString());
                int size = robotGroupDao.findCountByGroupId(groupId);
                group.setRobotNumber(size + 1);
                group.setUpdateDate(new Date());
                group.setUpdateBy(suser.getUserName());
                RobotGroup robotGroup = new RobotGroup();
                robotGroup.setGroupId(groupId);
                robotGroup.setRobotId(robotId);
                robotGroup.setIs_deleted("0");
                robotGroup.setCreateDate(new Date());
                robotGroup.setCreateBy(suser.getUserName());
                robotGroupDao.save(robotGroup);
                groupDao.save(group);
                robotDao.save(robot);
            }
        }catch (Exception e){
            throw new RuntimeException("向分组添加机器人失败！" + e.getMessage());
        }
        if(StringUtils.isNotBlank(group.getInPlanId())){
            try {
                playPlanService.curdPlanData(Long.parseLong(group.getInPlanId()));
            }catch (Exception e){
                logger.error("向分组增加机器人，同步远程接口的时候异常：" + e);
            }
        }

    }


    @Transactional
    public long createNewGroup(GroupVo groupVo){
        ShiroDbRealm.ShiroUser suser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if(suser == null){
            throw new RuntimeException("未登录！！！");
        }
        if(groupVo == null || StringUtils.isBlank(groupVo.getGroupName())){
            throw new NullPointerException("参数为空！！");
        }
        String groupName = groupVo.getGroupName();
        String groupId = groupVo.getGroupId();
        String companyId = groupVo.getCompanyId();
        try{
            Group group = groupDao.findGroupByNameAndCompanyId(groupName,companyId);
            if(group != null){
                if(StringUtils.isNotBlank(groupId)){
                    if(group.getId().toString().equals(groupId)){
                        group.setGroupName(groupName);
                        groupDao.save(group);
                    }else{
                        throw new RuntimeException("该分组名称已经存在");
                    }
                }else{
                    throw new RuntimeException("该分组名称已经存在");
                }
            }
            if(StringUtils.isNotBlank(groupId)){
                group = groupDao.findOne(Long.parseLong(groupId));
                if(group != null){
                    group.setGroupName(groupName);
                    groupDao.save(group);
                }
            }else{
                group = new Group();
                if(StringUtils.isBlank(groupVo.getGroupId())){
                    group = new Group();
                    group.setGroupName(groupName);
                    group.setCreateBy(suser.getUserName());
                    group.setCreateDate(new Date());
                    group.setIs_deleted("0");
                    group.setCompanyId(groupVo.getCompanyId());
                    group.setRobotNumber(0);
                    groupDao.save(group);
                }
            }
            return group.getId();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }


    }

    public PageImpl<GroupVo> findAllGroupVo(GroupVo groupVo){
        if(groupVo == null){
            throw new NullPointerException("查询实体为空");
        }
        PageInfo pageInfo = groupVo.getPageInfo();
        if(groupVo.getPageInfo()==null){
            pageInfo = new PageInfo();
            pageInfo.setPageSize(10);
        }
        PageRequest pageRequest = getPageRequestInfo(pageInfo);
        PageImpl<GroupVo> page = groupDao.findPageGroup(groupVo,pageRequest);
        return page;
    }

    private PageRequest getPageRequestInfo(PageInfo pageInfo){
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        return new PageRequest(pageInfo.getPageNumber() - 1,pageInfo.getPageSize(), sort);
    }


    public GroupVo findOneByGroupId(long groupId){
        Group group = groupDao.findOne(groupId);
        if(group != null && group.getIs_deleted().equals("0")){
            GroupVo groupVo = new GroupVo();
            BeanUtils.copyProperties(group,groupVo);
            groupVo.setGroupId(String.valueOf(group.getId()));
            return groupVo;
        }
        return null;
    }

    @Transactional
    public void robotGroupDelete(String groupId){
        if(planFileDao.findAllByGroupId(groupId) > 0){
            throw new RuntimeException("该分组已被播放计划使用");
        }
        Group group = groupDao.findOne(Long.parseLong(groupId));
        if(group != null && group.getIs_deleted().equals("0")){
            List<RobotGroup> list = robotGroupDao.findAllByGroupId(groupId);
            for(RobotGroup entity : list){
                Robot robot = robotDao.findOne(Long.parseLong(entity.getRobotId()));
                if(robot != null && robot.getIs_deleted().equals("0")){
                    robot.setInGroupId("");
                    robotDao.save(robot);
                }
                entity.setIs_deleted("1");
                entity.setUpdateDate(new Date());
                entity.setUpdateBy("admin");
                robotGroupDao.save(entity);
            }
            group.setRobotNumber(0);
            group.setIs_deleted("1");
            group.setUpdateDate(new Date());
            group.setUpdateBy("admin");
            groupDao.save(group);
        }
    }


    public PageImpl<RobotVo> findRobotPageByGroupId(String groupId, PageInfo pageInfo){
        if(pageInfo == null){
            pageInfo = new PageInfo();
            pageInfo.setPageSize(10);
        }
        PageRequest pageRequest = getPageRequestInfo(pageInfo);
        PageImpl<RobotVo> page = robotGroupDao.findPageRobotFromGroup(groupId,pageRequest);
        return page;
    }


    public String groupDeleteRobot(String groupId, String robotId){
        Group group = null;
        RobotGroup robotGroup = robotGroupDao.groupDeleteRobot(groupId,robotId);
        if(robotGroup!=null){
            Robot robot = robotDao.findOne(Long.parseLong(robotId));
            if(robot != null && robot.getIs_deleted().equals("0")){
                robot.setInGroupId(null);
                robotDao.save(robot);
            }
            robotGroup.setIs_deleted("1");
            robotGroup.setUpdateDate(new Date());
            robotGroup.setUpdateBy("admin");
            robotGroupDao.save(robotGroup);
            group = groupDao.findOne(Long.parseLong(groupId));
            group.setRobotNumber(robotGroupDao.findCountByGroupId(groupId));
            group.setUpdateBy("admin");
            group.setUpdateDate(new Date());
            groupDao.save(group);
            if(StringUtils.isNotBlank(group.getInPlanId())){
                try {
                    playPlanService.curdPlanData(Long.parseLong(group.getInPlanId()));
                }catch (Exception e){
                    logger.error("向分组增加机器人，同步远程接口的时候异常：" + e);
                }
            }
            return "1";
        }else{
            return "0";
        }
    }

    public void saveGroupInfo(GroupVo groupVo){
        Long groupId = 0l;
        String groupName = "";
        if(groupVo != null && StringUtils.isNotBlank(groupVo.getGroupId()) && StringUtils.isNotBlank(groupVo.getGroupName())){
            groupId = Long.parseLong(groupVo.getGroupId());
            groupName = groupVo.getGroupName();
        }else{
            throw new NullPointerException("请求参数为空");
        }
        if(groupDao.findGroupByNameAndCompanyId(groupName,groupVo.getCompanyId()) != null){
            throw new RuntimeException("该分组名称已经存在");
        };
        Group group = groupDao.findOne(groupId);
        group.setGroupName(groupName);
        group.setUpdateDate(new Date());
        ShiroDbRealm.ShiroUser suser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if(suser == null){
            throw new RuntimeException("未登录");
        }
        group.setUpdateBy(suser.getUserName());
        groupDao.save(group);
    }
    public void updateGroup(String planId,long groupId){
    	Group g = groupDao.findOne(groupId);
    	g.setInPlanId(planId);
    	groupDao.save(g);
    }

}
